
package com.yimixian.app.order;

import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mobileqq.openpay.api.IOpenApi;
import com.tencent.mobileqq.openpay.api.OpenApiFactory;
import com.tencent.mobileqq.openpay.constants.OpenConstants;
import com.tencent.mobileqq.openpay.data.pay.PayApi;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.common.YmxTitleBarActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Order;
import com.yimixian.app.model.QQWalletRespsonse;
import com.yimixian.app.model.QqwalletPayOrder;
import com.yimixian.app.model.WechatOrder;
import com.yimixian.app.payment.AlipayPayResult;
import com.yimixian.app.payment.PaymentController;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

public abstract class AbstractOrderActivity extends YmxTitleBarActivity {

    public String mPayMethod = "";

    public boolean mStartedWechatPay;
    public ProgressDialogFragment mProgressDialog;
    PaymentMethodView mPaymentMethodView;
    View mContentFrame;
    public TextView mCountDownTextView;
    FrameLayout mBottomBar;
    public DataManager mDataManager;
    public WechatOrder mWechatOrder;
    public QqwalletPayOrder mQqwalletPayOrder;
    public CountDownTimer mCountDownTimer;
    public Order mOrder;
    public IWXAPI mWxApi;
    public IOpenApi openApi;
    public boolean mIsPayFinished = false;
    public YmxDataService mYmxDataService;
    public String mPaymentId;
    public PaymentController mPaymentController;
    private String mAlipayString;
    private int mPaySerial = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if (mStartedWechatPay) {
//            onWechatPayFinished();
//        }
    }

    @Override
    protected void onResume() {
        if (mStartedWechatPay) {
            onWechatPayFinished();
        }
        if("qqwallet".equals(mPayMethod)) {
            mProgressDialog = UiUtils.dismiss(mProgressDialog);
            mPayMethod = "";
        }
        super.onResume();

    }

    /**
     * QQ钱包支付完成结果处理
     */
    private void onQQWalletPayFinish() {
        mProgressDialog = UiUtils.dismiss(mProgressDialog);
        boolean result = DataManager.getInstance().get(Constants.QQ_WALLET_RESPONSE_CODE);
        if(result) {
            onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_QQ_WALLET);
        } else {
            UiUtils.showToast(SystemFramework.getInstance().getGlobalContext(), "支付失败");
        }
    }

    public void initData() {
        mDataManager = DataManager.getInstance();
        mYmxDataService = YmxDataService.getInstance();
        mPaymentController = PaymentController.getInstance();
        mWxApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APP_ID);
        openApi = OpenApiFactory.getInstance(this, Constants.QQ_WALLET_APP_ID);
    }

    public void onWechatPayFinished() {
        mProgressDialog = UiUtils.dismiss(mProgressDialog);
        mStartedWechatPay = false;
        Integer resultCode = mDataManager.get(mWechatOrder.prepayid);
        if (resultCode != null && resultCode == BaseResp.ErrCode.ERR_OK) {
            onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_METHOD_WECHAT);
        } else {
            UiUtils.showToast(SystemFramework.getInstance().getGlobalContext(), "支付失败");
        }
    }

    public void onPaymentSucceeded(String paymentMethod) {
        UiUtils.showToast(this, "支付成功");
        if (!paymentMethod.equals(ConfirmOrderActivity.PAYMENT_METHOD_BALANCE)) {
            notifyPaySuc(mPaymentId, paymentMethod);
        }
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        mProgressDialog = UiUtils.dismiss(mProgressDialog);
        mBottomBar.setVisibility(View.GONE);
        mPaymentMethodView.setEnabled(false);
        ((FrameLayout.LayoutParams) mContentFrame.getLayoutParams()).bottomMargin = 0;
        if (!Strings.isNullOrEmpty(mOrder.successUrl)) {
            Intent intent = new Intent(this, WebViewActivity.class);
            intent.putExtra(WebViewActivity.EXTRA_URL, mOrder.successUrl);
            startActivity(intent);
            EventBus.getDefault().post(Constants.EVENT_BUS_PAY_SUC_UPDATE_CART);
            if (mIsPayFinished) {
                if (this instanceof OrderDetailActivity){
                    SharedPreferencesHelper.commitBoolean(Constants.PAY_SUCCESS, true);
                }
                finish();
            }
        }

    }

    public void payWithWechat() {
        mStartedWechatPay = true;
        PayReq request = new PayReq();
        request.appId = mWechatOrder.appid;
        request.partnerId = mWechatOrder.partnerid;
        request.prepayId = mWechatOrder.prepayid;
        request.packageValue = mWechatOrder.packageValue;
        request.nonceStr = mWechatOrder.noncestr;
        request.timeStamp = mWechatOrder.timestamp;
        request.sign = mWechatOrder.sign;
        mWxApi.registerApp(Constants.WECHAT_APP_ID);
        mWxApi.sendReq(request);
    }

    public void fetchWechatOrder(String payId) {
        if (mWechatOrder != null) {
            payWithWechat();
            return;
        }

        mYmxDataService.payWithWechat(payId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<WechatOrder>() {
                        @Override
                        public void call(WechatOrder wechatOrder) {
                            mWechatOrder = wechatOrder;
                            payWithWechat();
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            UiUtils.toastError(
                                SystemFramework.getInstance().getGlobalContext(), throwable);
                        }
                    });
    }

    public void countDownTimerStart(long countDown) {
        mCountDownTimer = new CountDownTimer(countDown * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int left = (int) (millisUntilFinished / 1000);
                int minute = left / 60;
                int second = left - minute * 60;
                mCountDownTextView.setText(String.format("支付倒计时 %02d:%02d", minute, second));
            }

            @Override
            public void onFinish() {
                onPaymentTimeout();
            }
        }.start();
    }

    public void onPaymentTimeout() {
        UiUtils.showToast(this, "支付超时");
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        mProgressDialog = UiUtils.dismiss(mProgressDialog);
        mBottomBar.setVisibility(View.GONE);
        ((FrameLayout.LayoutParams) mContentFrame.getLayoutParams()).bottomMargin = 0;
    }

    public void paymentButtonClicked(String mPaymentMethod) {
        String dialogText;
        switch (mPaymentMethod) {
            case (ConfirmOrderActivity.PAYMENT_METHOD_ALIPAY):
                dialogText = "打开支付宝...";
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_WECHAT):
                dialogText = "打开微信支付...";
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_BALANCE):
                dialogText = "支付中...";
                break;
            case (ConfirmOrderActivity.PAYMENT_QQ_WALLET):
                dialogText = "打开QQ钱包...";
                break;
            default:
                dialogText = "支付中...";
                break;
        }
        mProgressDialog = UiUtils.showProgressDialog(this, dialogText);
        String payId = mPaymentId;
        if (TextUtils.isEmpty(payId)) {
            if (mOrder != null) {
                payId = mOrder.paymentId;
            }
        }
        if (!TextUtils.isEmpty(payId)) {
            startPayment(mPaymentMethod, payId);
            return;
        }
    }

    public void startPayment(String mCurrentPayMethodName, String payId) {
        switch (mCurrentPayMethodName) {
            case (ConfirmOrderActivity.PAYMENT_METHOD_ALIPAY):
                fetchAlipayString(payId);
                MobclickAgent.onEvent(this, StatConstants.CONFIRM_ORDER_ALIPAY_CLICK);
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_WECHAT):
                MobclickAgent.onEvent(this, StatConstants.CONFIRM_ORDER_WECHAT_CLICK);
                fetchWechatOrder(payId);
                break;
            case (ConfirmOrderActivity.PAYMENT_QQ_WALLET):
                fetchQQWolletOrder(payId);
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_BALANCE):
                MobclickAgent.onEvent(this, StatConstants.CONFIRM_ORDER_BALANCE_CLICK);
                payWithBalance(payId);
                break;
        }
    }

    /**
     * 获取QQ支付所需的信息
     * @param payId
     */
    private void fetchQQWolletOrder(String payId) {
        if (mQqwalletPayOrder != null && openApi != null) {
            boolean isInstalled = openApi.isMobileQQInstalled();
            boolean isSupport = openApi.isMobileQQSupportApi(OpenConstants.API_NAME_PAY);
            if(isInstalled && isSupport) {
                payWithQQWallet();
            } else {
                if(mProgressDialog != null) {
                    mProgressDialog = UiUtils.dismiss(mProgressDialog);
                }
                UiUtils.showToast("您没有安装QQ或QQ版本过低");
            }
            return;
        }

        mYmxDataService.payWithQQWallet(payId)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                new Action1<QqwalletPayOrder>() {
                    @Override
                    public void call(QqwalletPayOrder qqwalletPayOrder) {
                        mQqwalletPayOrder = qqwalletPayOrder;
                        boolean isInstalled = openApi.isMobileQQInstalled();
                        boolean isSupport = openApi.isMobileQQSupportApi(OpenConstants.API_NAME_PAY);
                        if(isInstalled && isSupport) {
                            payWithQQWallet();
                        } else {
                            if(mProgressDialog != null) {
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            }
                            UiUtils.showToast("您没有安装QQ或QQ版本过低");
                        }

                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mProgressDialog = UiUtils.dismiss(mProgressDialog);
                        UiUtils.toastError(
                            SystemFramework.getInstance().getGlobalContext(), throwable);
                    }
                });
    }

    /**
     * QQ钱包支付
     */
    private void payWithQQWallet() {
        PayApi api = new PayApi();
        mPayMethod = "qqwallet";
        api.appId = Constants.QQ_WALLET_APP_ID;
        api.serialNumber = ""+ mPaySerial++;
        api.callbackScheme = Constants.QQ_WALLET_SCHEME;
        api.tokenId = mQqwalletPayOrder.tokenid;
        api.pubAcc = mQqwalletPayOrder.pubacc;
        api.pubAccHint = mQqwalletPayOrder.pubacchint;
        api.nonce = mQqwalletPayOrder.nonce;
        api.timeStamp = System.currentTimeMillis() / 1000;
        api.bargainorId = mQqwalletPayOrder.bargainorid;
        api.sig = mQqwalletPayOrder.sig;
        api.sigType = "HMAC-SHA1";
        if (api.checkParams()) {
            openApi.execApi(api);
        }
    }

    private void fetchAlipayString(String payId) {
        if (mAlipayString != null) {
            payWithAlipay();
            return;
        }

        mYmxDataService.payWithAlipay(payId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<String>() {
                            @Override
                            public void call(String alipayOrderString) {
                                mAlipayString = alipayOrderString;
                                payWithAlipay();
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                UiUtils.toastError(
                                        SystemFramework.getInstance().getGlobalContext(), throwable);
                            }
                        });
    }

    private void payWithAlipay() {
        mPaymentController.payWithAlipay(mAlipayString, AbstractOrderActivity.this)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<AlipayPayResult>() {
                            @Override
                            public void call(AlipayPayResult result) {
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);

                                if (TextUtils.equals(result.getResultStatus(), "9000")) {
                                    onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_METHOD_ALIPAY);
                                } else {
                                    UiUtils.showToast(AbstractOrderActivity.this, result.getMemo());
                                }
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                UiUtils.toastError(AbstractOrderActivity.this, throwable, "支付异常");
                            }
                        });
    }

    private void payWithBalance(String payId) {

        mYmxDataService.payWithBalance(payId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<Boolean>() {
                            @Override
                            public void call(Boolean result) {
                                onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_METHOD_BALANCE);
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                UiUtils.toastError(
                                        SystemFramework.getInstance().getGlobalContext(), throwable);
                            }
                        });
    }

    public void notifyPaySuc(String mPaymentId, String paymentmethod) {
        mYmxDataService.notifyPaySuc(mPaymentId, paymentmethod)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<String>() {
                            @Override
                            public void call(String info) {
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {

                            }
                        }
                );
    }

    @Override
    protected void onDestroy() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void initView() {
        mPaymentMethodView = (PaymentMethodView) findViewById(R.id.pay_method_view);
        mContentFrame = findViewById(R.id.content_frame);
        mCountDownTextView = (TextView) findViewById(R.id.count_down_text);
        mBottomBar = (FrameLayout) findViewById(R.id.bottom_bar);
    }

    public void onEventMainThread(QQWalletRespsonse message) {
        if (message != null) {
            if(message.response) {
                onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_QQ_WALLET);
            } else {
                UiUtils.showToast(SystemFramework.getInstance().getGlobalContext(), "支付失败");
            }
        } else {
            UiUtils.showToast(SystemFramework.getInstance().getGlobalContext(), "支付失败");
        }
    }
}
